package com.test.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

@Slf4j
public class MD5Utils {

    public static String getMD5(InputStream is) {

        StringBuilder md5 = new StringBuilder();

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] dataBytes = new byte[1024];

            int nread;
            while ((nread = is.read(dataBytes)) != -1) {
                md.update(dataBytes, 0, nread);
            }

            byte[] mdbytes = md.digest();

            // convert the byte to hex format
            for (byte mdbyte : mdbytes) {
                md5.append(Integer.toString((mdbyte & 0xff) + 0x100, 16).substring(1));
            }
        } catch (Exception e) {
            log.error("获取MD5失败|{}", e.getMessage());
        }

        return md5.toString();
    }

    /**
     * 获取文件MD5
     */
    public static String getMD5(File file) {

        String md5 = null;
        try {
            InputStream is = new FileInputStream(file);
            md5 = getMD5(is);
            is.close();
        } catch (Exception e) {
            log.error("获取MD5失败|{}", e.getMessage());
        }
        return md5;
    }

    /**
     * 获取字符串MD5
     */
    public static String getMD5(String string) {

        log.debug("获取字符串MD5|{}", string);

        StringBuilder sb = new StringBuilder(40);
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(string.getBytes(StandardCharsets.UTF_8));
            for (byte x : bs) {
                if ((x & 0xff) >> 4 == 0) {
                    sb.append("0").append(Integer.toHexString(x & 0xff));
                } else {
                    sb.append(Integer.toHexString(x & 0xff));
                }
            }
        } catch (Exception e) {
            log.error("获取MD5失败|{}", e.getMessage());
        }
        return sb.toString();
    }
}
